package com.sichen.product.service.impl;

import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sichen.common.constant.ProductConstant;
import com.sichen.common.to.SkuReductionTo;
import com.sichen.common.to.SpuBoundTo;
import com.sichen.common.to.es.SkuEsModel;
import com.sichen.common.utils.PageUtils;
import com.sichen.common.utils.Query;
import com.sichen.common.utils.R;
import com.sichen.product.dao.SpuInfoDao;
import com.sichen.product.entity.*;
import com.sichen.product.feign.CouponFeignService;
import com.sichen.product.feign.SearchFeignService;
import com.sichen.product.feign.WareFeignService;
import com.sichen.product.service.*;
import com.sichen.product.vo.SkuHasStockVo;
import com.sichen.product.vo.SpuSaveVO.BaseAttrs;
import com.sichen.product.vo.SpuSaveVO.Bounds;
import com.sichen.product.vo.SpuSaveVO.Images;
import com.sichen.product.vo.SpuSaveVO.Skus;
import com.sichen.product.vo.SpuSaveVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    SpuInfoDescService spuInfoDescService;

    @Resource
    SpuImagesService spuImagesService;

    @Resource
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrService attrService;

    @Resource
    SkuInfoService skuInfoService;

    @Resource
    SkuImagesService skuImagesService;

    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }


    /**
     * 保存商品信息
     *
     * @param vo 传递的商品信息
     */
    @Override
    @Transactional //保存数据较多 ， 需要满足全部完成
    public void saveSpuInfo(SpuSaveVo vo) {

        //1.保存spu基本信息: pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        Long spuId = spuInfoEntity.getId();

        //2，保存spu的描述图片: pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        //这里的 Spu_id 不是自动生成的 ， 所以在上一步保存之后 ， 就可以获取保存对象的Spu_id
        descEntity.setSpuId(spuId);
        //将数组中的所有数据拼接起来 , 用 , 隔开
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3.保存spu的图片集: pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuId, images);

        //4.保存spu的规格参数: pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        productAttrValueService.saveProductAttrValue(spuId, baseAttrs);

        // 5.保存spu的积分信息: sichen_sms -> sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        // 6.保存当前spu对应的所有sku信息:
        List<Skus> skus = vo.getSkus();
        //判断是否为空
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultImg = "";
                //判断是否是默认图片
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }

                // 6.1). 保存sku的基本信息： pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                // 6.2). sku的图片信息： pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //filter 返回true就是需要 , 返回false就是不需要 , 进行舍弃的
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                // 6.3). sku的销售优惠属性信息 ：pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = item.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 6.4). sku的优惠.满减等信息 ： sichen_sms -> sms_sku_ladder | sms_sku_full_reduction | sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        // 检索关键字不为空
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((w) -> w.eq("id", key).or().like("spu_name", key));
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);

        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)) {
            queryWrapper.eq("brand_id", brandId);

        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        // 1.组装需要的数据
        // 1.1 查出当前spuId对应的所有sku信息 , 品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        // 4.查询当前sku的所有可以被用来检索的规格属性
        // 当前SPU的所有属性
        List<ProductAttrValueEntity> baseAttr = productAttrValueService.baseAttrListForSpu(spuId);
        // 获取所有的属性id集合
        List<Long> attrIds = baseAttr.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        // 根据所有属性id查询出可以被检索的属性id集合
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        // 获取可以被检索的属性的全部信息
        List<SkuEsModel.Attrs> attrsList = baseAttr.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());

        // TODO:1. 发送远程调用库存系统 , 查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            R stock = wareFeignService.getSkusHasStock(skuIds);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = stock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常:原因{}", e.getMessage());
        }
        // 2.封装每个模型的sku信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skuInfoEntities.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            // 1.设置库存信息
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            // 2. 热度评分 , 新上架的商品默认为 0 , 可能按照实际需求 , 给设置不同的值
            esModel.setHotScore(0L);
            // 3.查询品牌数据
            BrandEntity brandEntity = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());
            // 4.分类的名称数据
            CategoryEntity categoryEntity = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(categoryEntity.getName());
            esModel.setAttrs(attrsList);
            return esModel;
        }).collect(Collectors.toList());

        // 5.将数据发送给es进行保存 , sichen-search
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0) {
            // 5.1. 远程调用成功 , 修改当前spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.statusEnum.SPU_UP.getCode());
        } else {
            // 远程调用失败
            // TODO  5.2. 重复调用? 接口幂等性:重试机制?
            // Feign调用流程
            /*
            * 1.构造请求数据 , 将对象转为json
            *   RequestTemplate template = buildTemplateFromArgs.create(argv);
            * 2.发送请求进行执行 (执行成功会解码响应数据)
            *   executeAndDecode(template);
            * 3.执行请求会有重试机制
            *   while(true){
            *      try{
            *           executeAndDecode(template)
            *       }catch(e) {
            *           try{
            *               retryer.continueOrPropagate(e);
            *           }catch(e){
            *               throw ex;
            *           }
            *           continue;
            *       }
            * }
            * */
        }
    }


}